#include<iostream>
#include<cstring>
#include<cerrno>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Comm.hpp"
#include"nocopy.hpp"
#include"Log.hpp"
#include<unistd.h>

using namespace LogModule;

void Usage(const std::string & process)
{
    std::cout << "Usage: " << process << " server_ip server_port"<< std::endl;
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    //创建socket
    int sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock<0)
    {
        LOG(LogModule::LogLevel::ERROR)<<"socket error,"<<errno<<":"<<strerror(errno);
        exit(Socket_Err);
    }
    std::cout<<"create socket success"<<std::endl;
    //client 一定要绑定port,但是不需要显示绑定，因为在第一次发数据时会自动绑定
    //server的 port众所周知不能更改，而client不需要，因此自动绑定即可
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());//将点分十进制字符串ip转为uint32
    //也可以使用inet_pton函数，inet_pton(AF_INET,serverip.c_str(),server.sin_addr.s_addr)，将ip由点分十进制转换为uint32
    int n=connect(sock,CONV(&server),sizeof(server));//申请建立连接
    if(n<0)
    {
        std::cout<<"建立连接失败"<<std::endl;
        exit(Connect_Err);
    }
    while(true)
    {
        std::string inbuffer;
        std::cout<<"please enter#:";
        std::getline(std::cin,inbuffer);
        ssize_t n=write(sock,inbuffer.c_str(),inbuffer.size());
        if(n>0)
        {
            char buffer[1024];
            ssize_t m=read(sock,buffer,sizeof(buffer));
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<buffer<<std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(sock);
    return 0;
}